package guoanmaker.operator.business.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.modelnobind.DailyRegisteredUserVolumeMove;
import guoanmaker.operator.business.modelnobind.PersonalUserLandLogMove;
import guoanmaker.operator.business.modelnobind.PersonalUserMove;
import guoanmaker.operator.business.modelnobind.ProvideOrderFormForOrder;
import guoanmaker.operator.business.repository.PersonalUserRepository;

@Service
public class OperatorHomePageService implements OperatorHomePageServiceInterface {

	@PersistenceContext
	private EntityManager manager;
	
	@Autowired
	private PersonalUserRepository personalUserRepository;
	
	public Map<String,Object> userRegistrationInformation(){
		Map<String,Object> map=new HashMap<String,Object>();
		PersonalUserMove personalUserMove=null;
		PersonalUserLandLogMove personalUserLandLogMove=null;
		//查询用户注册总数
		Long userRegistrationNumber=0L;
		userRegistrationNumber=	personalUserRepository.selectBycontId();
		map.put("userRegistrationNumber", userRegistrationNumber);
		//分组查询   app   pc  注册数量
		Long appUserRegistrationNumber=0L;
		Long pcUserRegistrationNumber=0L;
		String jpql1="select new guoanmaker.operator.business.modelnobind.PersonalUserMove(u.createType,count(1)) from "
				+ "PersonalUser u where u.createType in (1,2) group by u.createType";
		Query query1=manager.createQuery(jpql1);
		List list=query1.getResultList();
		if(list!=null&&list.size()==1){
			personalUserMove=(PersonalUserMove)list.get(0);
			String createType=personalUserMove.getCreateType();
			if(createType!=null&&createType.equals("1")){
				pcUserRegistrationNumber=personalUserMove.getCount();
			}
			else if(createType!=null&&createType.equals("2")){
				appUserRegistrationNumber=personalUserMove.getCount();
			}
		}
		else if(list!=null&&list.size()==2){
			personalUserMove=(PersonalUserMove)list.get(0);
			String createType=personalUserMove.getCreateType();
			if(createType!=null&&createType.equals("1")){
				pcUserRegistrationNumber=personalUserMove.getCount();
			}
			else if(createType!=null&&createType.equals("2")){
				appUserRegistrationNumber=personalUserMove.getCount();
			}
			personalUserMove=(PersonalUserMove)list.get(1);
			createType=personalUserMove.getCreateType();
			if(createType!=null&&createType.equals("1")){
				pcUserRegistrationNumber=personalUserMove.getCount();
			}
			else if(createType!=null&&createType.equals("2")){
				appUserRegistrationNumber=personalUserMove.getCount();
			}
		}
		map.put("appUserRegistrationNumber", appUserRegistrationNumber);
		map.put("pcUserRegistrationNumber", pcUserRegistrationNumber);
		//服务商注册数量
		Long businessRegistrationNumber=0L;
		String jpql2="select new guoanmaker.operator.business.modelnobind.PersonalUserMove(count(1)) from  PersonalUser u "
				+ "where u.isProvider in (2,4)";
		Query query2=manager.createQuery(jpql2);
		personalUserMove=(PersonalUserMove)query2.getResultList().get(0);
		businessRegistrationNumber=personalUserMove.getCount();
		map.put("businessRegistrationNumber", businessRegistrationNumber);
		//日活跃数量    app活跃数量    pc活跃 
		Long dayUserRegistrationNumber=0L;
		Long dayAppUserRegistrationNumber=0L;
		Long dayPcUserRegistrationNumber=0L;
		String jpql3="select new guoanmaker.operator.business.modelnobind.PersonalUserLandLogMove(u.landType,count(u.landCount)) from "
				+ "PersonalUserLandLog u where to_days(u.landTime) = to_days(now()) GROUP BY u.landType";
		Query query3=manager.createQuery(jpql3);
		List list3=query3.getResultList();
		if(list3!=null&&list3.size()==1){
			personalUserLandLogMove=(PersonalUserLandLogMove)list3.get(0);
			String landType=personalUserLandLogMove.getLandType();
			if(landType!=null&&landType.equals("1")){
				dayPcUserRegistrationNumber=personalUserLandLogMove.getCount();
			}
			else if(landType!=null&&landType.equals("2")){
				dayAppUserRegistrationNumber=personalUserLandLogMove.getCount();
			}
		}
		else if(list3!=null&&list3.size()==2){
			personalUserLandLogMove=(PersonalUserLandLogMove)list3.get(0);
			String landType=personalUserLandLogMove.getLandType();
			if(landType!=null&&landType.equals("1")){
				dayPcUserRegistrationNumber=personalUserLandLogMove.getCount();
			}
			else if(landType!=null&&landType.equals("2")){
				dayAppUserRegistrationNumber=personalUserLandLogMove.getCount();
			}
			personalUserLandLogMove=(PersonalUserLandLogMove)list3.get(1);
			landType=personalUserLandLogMove.getLandType();
			if(landType!=null&&landType.equals("1")){
				dayPcUserRegistrationNumber=personalUserLandLogMove.getCount();
			}
			else if(landType!=null&&landType.equals("2")){
				dayAppUserRegistrationNumber=personalUserLandLogMove.getCount();
			}
		}
		dayUserRegistrationNumber= dayPcUserRegistrationNumber+dayAppUserRegistrationNumber;
		map.put("dayPcUserRegistrationNumber", dayPcUserRegistrationNumber);
		map.put("dayAppUserRegistrationNumber", dayAppUserRegistrationNumber);
		map.put("dayUserRegistrationNumber", dayUserRegistrationNumber);
		return map;
	}
	//每日注册量查询
	public List<DailyRegisteredUserVolumeMove> dailyRegisteredUserVolume(Integer time){
		Calendar nows=Calendar.getInstance();
		nows.setTime(new Date());
		nows.add(Calendar.DATE, -time);
		Date date=nows.getTime();
		String jpql="select new guoanmaker.operator.business.modelnobind.DailyRegisteredUserVolumeMove(date_format(u.createTime,'%Y-%m-%d'),count(1))"
				+ " from PersonalUser u where u.createTime>:date GROUP BY date_format(u.createTime,'%Y-%m-%d')";
		Query query=manager.createQuery(jpql).setParameter("date", date);
		List<DailyRegisteredUserVolumeMove> list=query.getResultList();
		return list;
	}
	//用户商户量比
	public Map<String,List<Object>> userVolumeRatio(Integer time){
		Map<String,List<Object>> map=new HashMap<String,List<Object>>();
		String jpql="select new guoanmaker.operator.business.modelnobind.DailyRegisteredUserVolumeMove(date_format(u.createTime, '%Y-%m'),"
				+ "count(1)) from PersonalUser u where YEAR(u.createTime)="
				+ ":time GROUP BY date_format(u.createTime, '%Y-%m')";
		Query query=manager.createQuery(jpql).setParameter("time", time);
		List<DailyRegisteredUserVolumeMove> list=query.getResultList();
		DailyRegisteredUserVolumeMove dailyRegisteredUserVolumeMove=null;
		List<Object> listint=new ArrayList<Object>();
		int n=0;
		for (int i = 1; i < 13; i++) {
			try {
				dailyRegisteredUserVolumeMove=list.get(n);
				String date=dailyRegisteredUserVolumeMove.getDayDate();
				int a=Integer.parseInt(date.substring(5,7));
				if(a==i){
					listint.add(dailyRegisteredUserVolumeMove.getDayCount());
					n++;
				}
				else{
					listint.add(0);
				}
			} catch (Exception e) {
				listint.add(0);
			}
		}
		map.put("user", listint);
		String jpql1="select new guoanmaker.operator.business.modelnobind.DailyRegisteredUserVolumeMove(date_format(u.isProviderTime, '%Y-%m'),"
				+ "count(1)) from PersonalUser u where YEAR(u.isProviderTime)="
				+ ":time GROUP BY date_format(u.isProviderTime, '%Y-%m')";
		Query query1=manager.createQuery(jpql1).setParameter("time", time);
		List<DailyRegisteredUserVolumeMove> list1=query1.getResultList();
		List<Object> listints=new ArrayList<Object>();
		dailyRegisteredUserVolumeMove=null;
		int nn=0;
		for (int i = 1; i < 13; i++) {
			try {
				dailyRegisteredUserVolumeMove=list1.get(nn);
				String date=dailyRegisteredUserVolumeMove.getDayDate();
				int a=Integer.parseInt(date.substring(5,7));
				if(a==i){
					listints.add(dailyRegisteredUserVolumeMove.getDayCount());
					nn++;
				}
				else{
					listints.add(0);
				}
			} catch (Exception e) {
				listints.add(0);
			}
		}
		map.put("business", listints);
		return map;
	}
	public Map<String,Object> VolumeStatistics(){
		Map<String,Object> map=new HashMap<String,Object>();
		ProvideOrderFormForOrder provideOrderFormForOrder=null;
		//下单量统计
		Long orderQuantity=0L;
		String jpql="select new guoanmaker.operator.business.modelnobind.ProvideOrderFormForOrder(count(1)) from ProvideOrderForm";
		Query query=manager.createQuery(jpql);
		provideOrderFormForOrder=(ProvideOrderFormForOrder)query.getResultList().get(0);
		orderQuantity=provideOrderFormForOrder.getCount();
		map.put("orderQuantity", orderQuantity);
		//成交量统计   最终成功交易了多少   优惠了多少
		Long volume=0L;
		Double preferentialAmount=0.0;    //实际成交金额
		Double preferentialMoney=0.0;    //实际优惠金额
		String jpql2="SELECT new guoanmaker.operator.business.modelnobind.ProvideOrderFormForOrder(count(1),ROUND(sum(p.realPrice),2),"
				+ "ROUND(sum(p.preferentialMoney),2)) from ProvideOrderForm p where p.orderStatus in (6,13,2,3,4) OR (p.orderStatus =8 and "
				+ "p.fullOrPartRefunds=1) OR (p.orderStatus =12 and p.fullOrPartRefunds=1)";
		Query query2=manager.createQuery(jpql2);
		provideOrderFormForOrder=(ProvideOrderFormForOrder)query2.getResultList().get(0);
		volume=provideOrderFormForOrder.getCount();
		preferentialAmount=provideOrderFormForOrder.getPreferentialAmount();
		preferentialMoney=provideOrderFormForOrder.getPreferentialMoney();
		map.put("volume", volume);
		map.put("preferentialAmount", preferentialAmount);
		map.put("preferentialMoney", preferentialMoney);
		//查询所有已经支付过的金额包含退款的
		Double allAmount=0.0;  //所有已支付的
		String jpql1="SELECT new guoanmaker.operator.business.modelnobind.ProvideOrderFormForOrder(ROUND(sum(t.truePrice),2)) "
				+ "from ProvideOrderForm t where t.orderStatus!=1 and t.orderStatus!=7 and t.orderStatus!=14";
		Query query1=manager.createQuery(jpql1);
		provideOrderFormForOrder=(ProvideOrderFormForOrder)query1.getResultList().get(0);
		allAmount=provideOrderFormForOrder.getAllAmount();
		map.put("allAmount", allAmount);
		//发生退款的返还的优惠金额
		Double returnAmount=0.0;  //所有已支付的
		String jpql5="SELECT new guoanmaker.operator.business.modelnobind.ProvideOrderFormForOrder(ROUND(sum(t.returnPreferentialMoney),2)) "
				+ "from ProvideOrderForm t where t.orderStatus in (8,9,10,11)";
		Query query5=manager.createQuery(jpql5);
		provideOrderFormForOrder=(ProvideOrderFormForOrder)query5.getResultList().get(0);
		returnAmount=provideOrderFormForOrder.getAllAmount();
		map.put("returnAmount", returnAmount);
		//成功退款多少
		Double refundsAmount=0.0;//成功退款金额
		String jpql3="SELECT new guoanmaker.operator.business.modelnobind.ProvideOrderFormForOrder(ROUND(sum(p.refundsAmount),2)"
				+ ") from ProvideOrderForm p where p.orderStatus in (8,12) ";
		Query query3=manager.createQuery(jpql3);
		provideOrderFormForOrder=(ProvideOrderFormForOrder)query3.getResultList().get(0);
		refundsAmount=provideOrderFormForOrder.getAllAmount();
		map.put("refundsAmount", refundsAmount);
		//处于退款过程中的金额
		Double refundsAmountProdore=0.0;//退款中金额
		String jpql4="SELECT new guoanmaker.operator.business.modelnobind.ProvideOrderFormForOrder(ROUND(sum(p.refundsAmount),2)"
				+ ") from ProvideOrderForm p where p.orderStatus in (5,9,10,11) ";
		Query query4=manager.createQuery(jpql4);
		provideOrderFormForOrder=(ProvideOrderFormForOrder)query4.getResultList().get(0);
		refundsAmountProdore=provideOrderFormForOrder.getAllAmount();
		map.put("refundsAmountProdore", refundsAmountProdore);
		return map;
	}
	//查询成交量、金额趋势图
	public Map<String,Object> VolumeSumMap(Date strartTime,Date endTime ){
		Calendar nows=Calendar.getInstance();
		nows.setTime(endTime);
		nows.add(Calendar.DATE, 1);
		String jpql="SELECT new guoanmaker.operator.business.modelnobind.DailyRegisteredUserVolumeMove(date_format(p.defrayTime, '%Y%m%d'), count(1), "
				+ "sum(p.realPrice)) FROM ProvideOrderForm p WHERE p.orderStatus IN (6, 13) and p.defrayTime>=:strartTime and p.defrayTime<=:endTime OR (  p.orderStatus = 8 AND "
				+ "p.fullOrPartRefunds = 1 and p.defrayTime>=:strartTime and p.defrayTime<=:endTime) OR (p.orderStatus = 12 "
				+ "AND p.fullOrPartRefunds = 1 and p.defrayTime>=:strartTime and p.defrayTime<=:endTime) GROUP BY date_format(p.defrayTime, '%Y-%m-%d')";
		Query query=manager.createQuery(jpql).setParameter("strartTime", strartTime).setParameter("endTime", nows.getTime());
		List<DailyRegisteredUserVolumeMove> list=query.getResultList();//查询成交量与金额
		
		String jpql1="SELECT new guoanmaker.operator.business.modelnobind.DailyRegisteredUserVolumeMove(date_format(place_order_time, "
				+ "'%Y%m%d'),count(*)) from ProvideOrderForm p where p.placeOrderTime >= :strartTime and p.placeOrderTime <= :endTime "
				+ "GROUP BY date_format(p.placeOrderTime, '%Y-%m-%d')";
		Query query1=manager.createQuery(jpql1).setParameter("strartTime", strartTime).setParameter("endTime", nows.getTime());
		List<DailyRegisteredUserVolumeMove> lists=query1.getResultList();//查询下单量
		
		List<Object> listidate=new ArrayList<Object>();  //日期数组
		List<Object> listiorderQuantity=new ArrayList<Object>();  //下单量
		List<Object> listidateAmount=new ArrayList<Object>();  //金额
		List<Object> listidateVolume=new ArrayList<Object>(); //成交量
		DailyRegisteredUserVolumeMove dailyRegisteredUserVolumeMove=null;
		DailyRegisteredUserVolumeMove dailyRegisteredUserVolumeMove1=null;
		nows.setTime(strartTime);
		boolean a=true;
		int n=0;
		int m=0;
		while(a){
			SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd");
			listidate.add(sdfs.format(nows.getTime()));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			int starttime=Integer.parseInt(sdf.format(nows.getTime()));
			int endtime=Integer.parseInt(sdf.format(endTime));
			try {
				dailyRegisteredUserVolumeMove=list.get(n);
				int date=Integer.parseInt(dailyRegisteredUserVolumeMove.getDayDate());
				if(starttime==date){
					listidateVolume.add(dailyRegisteredUserVolumeMove.getDayCount());
					listidateAmount.add(dailyRegisteredUserVolumeMove.getDayAmont());
					n++;
				}
				else{
					listidateVolume.add(0);
					listidateAmount.add(0);
				}
			} catch (IndexOutOfBoundsException e) {
				listidateVolume.add(0);
				listidateAmount.add(0);
			}
			try {
				dailyRegisteredUserVolumeMove1=lists.get(m);
				int date1=Integer.parseInt(dailyRegisteredUserVolumeMove1.getDayDate());
				if(starttime==date1){
					listiorderQuantity.add(dailyRegisteredUserVolumeMove1.getDayCount());
					m++;
				}
				else{
					listiorderQuantity.add(0);
				}
			} catch (IndexOutOfBoundsException e) {
				listiorderQuantity.add(0);
			}
			nows.add(Calendar.DATE, 1);
			if(starttime == endtime){
				a=false;
			}
		}
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("listidate", listidate);
		map.put("listiorderQuantity", listiorderQuantity);
		map.put("listidateAmount", listidateAmount);
		map.put("listidateVolume", listidateVolume);
		return map;
	}
}
